
// 点击登录按钮出现登录界面
function getLogin() {
    $('.loginBtn').on('click', function () {
        if($('.loginBtn span:nth-child(2)').text() == '登录/注册')
        $('#login>div').css('display', 'block')
        $('#login .guanbi').on('click', function () {
            $('#login>div').css('display', 'none')
        })
    })
}
// 切换注册与登录界面
function changeLogin(){
    $('#login form>div').on('click','div',function(e){
        let target = e.target || e.srcElement
        if($(target).text() == '登录'){
            $('#login form>div>div').removeClass('active')
            $(target).addClass('active')
            $('#login form input[value="注册"]').val('登录')
        }
        if($(target).text() == '注册'){
            $('#login form>div>div').removeClass('active')
            $(target).addClass('active')
            $('#login form input[value="登录"]').val('注册')
        }
    })
}
// 输入账号密码进行注册
function register(){
    // 点击注册按钮后获取input中值连接数据库进行注册
    $('#login form').on('click','input[value="注册"]',async function(){
        // 获取input--value值
        let username = $('input[name="username"]').val()
        let password = $('input[name="password"]').val()
        let data = await myPromise({
            method: 'post',
            url: 'http://api.yuguoxy.com/api/member/add',
            data:{
                username,
                password
            }
        })
        if (data.resultCode == 1) {
            let registerStr = data.resultCode == 1 ? data.resultInfo : []
            console.log(registerStr,username,password)
            let newuser = {
                username,
                password
            }
            console.log(newuser)
            let userLocalStr = localStorage.getItem('user')
            let userlocal = JSON.parse(userLocalStr) || []
            userlocal.push(newuser)
            localStorage.setItem('user',JSON.stringify(userlocal))
            alert('会员信息注册成功，请登录！')
        }
    })
}

// 输入账号及密码从localStorage会员信息
function login() {
    // 点击提交按钮之后获取input值与数据库确认信息
    $('#login form').on('submit', async function (e) {
        e = e || window.event //事件对象
        e.preventDefault() //阻止默认行为
        // 调用登录接口 
        let username = $('input[name="username"]').val()
        let password = $('input[name="password"]').val()
        let data = await myPromise({
            method: 'post',
            url: 'http://api.yuguoxy.com/api/member/login',
            data:{
                username,
                password
            }
        })
        if (data.resultCode == 1) {
            let user = data.resultCode == 1 ? data.resultInfo : []
            console.log(user)
            // let userLocalStr = localStorage.getItem('userInfo')
            // let userlocal = JSON.parse(userLocalStr) || []
            // userlocal.push(user)
            localStorage.setItem('userInfo',JSON.stringify(user))
            alert('登录成功')
            $('#login>div').css('display', 'none')
            $('.loginBtn').html(`<div><img src="${user.headerimg}" alt=""></div>
            <span>${user.username}</span><span class="logout">退出登录</span>`)
            
        }
    })
    
}
// 从localStorage中获取用户信息并展示到页面
function showUser(){
    let userStr = localStorage.getItem('userInfo')
    if(userStr){
    let user = JSON.parse(userStr)
    $('.loginBtn').html(`<div><img src="${user.headerimg}" alt=""></div>
    <span>${user.username}</span><span class="logout">退出登录</span>`)
    logout()
}
}

showUser()
// 点击退出登录按钮退出登录
function logout(){
    $('.logout').on('click',function(){
        localStorage.removeItem('userInfo')
        $('.loginBtn').html(`<span class="iconfont icon-denglu"></span>
        <span>登录/注册</span>`)
    })
}
// 获取banner列表展示到页面
async function getBanner() {
    let data = await myPromise({
        method: 'get',
        url: 'http://api.yuguoxy.com/api/shop/banner'
    })
    if (data.resultCode == 1) {
        let banner = data.resultCode == 1 ? data.resultInfo : []
        getBannerHtml(banner.list)
    }
}

//渲染banner轮播图
function getBannerHtml(list) {
    let bannerStr = ` <div class="swiper">
    <div class="swiper-wrapper">`
    let str = list.map(item => {
        return `<div class="swiper-slide"><img src="${item.url}" alt=""></div>`
    }).join('')
    bannerStr = bannerStr + str + ` </div>
    
    <div class="swiper-pagination"></div>
    
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
    
    <div class="swiper-scrollbar"></div>
</div>`
    $('.banner').html(bannerStr)
    new Swiper('.swiper', {
        loop: true, // 循环模式选项
        autoplay: {
            delay: 500,
            stopOnLastSlide: false,
            disableOnInteraction: true,
            },
        speed:1000,
        // 如果需要分页器
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
    })
}
// 获取商品列表
let productListAll = ''
async function getProductList(pageNo){
    let data = await myPromise({
        method:'get',
        url:'http://api.yuguoxy.com/api/shop/list',
        data: {
            pageNo,
            pageSize:8
        }
    })
    if (data.resultCode == 1) {
        let product = data.resultCode == 1 ? data.resultInfo : []
        console.log(product)
        getProductListHtml(product.list)
    }
}
function getProductListHtml(list){
    let str = list.map(item =>{
        return `<li onclick="onProductDetail(${item.id})">
        <div class="proimg"><img src="${item.picture}" alt=""></div>
        <div class="protext">
            <span>${item.shop}</span>
            <span>淘宝</span>
            <span>包邮</span>
            <span>￥<span>${item.price}</span></span>
            <span>${item.oldprice}人已买</span>
        </div>
    </li>`
    })
    productListAll = productListAll + str
    $('.productlist>ul').html(productListAll)
}
// 点击加载更多，获取更多商品
function getMore(){
    let pageNo = 1
    $('.productMore').on('click',function(){
        getProductList(++pageNo)
    })
}
// 鼠标移入侧边栏菜单显示更多分类
function getMoreClassify(){
    $('#mainContent .left ul').on('mouseover','li',function(){
        let index  = $(this).index()
        console.log(index)
        $('.moreClassify').css('display','none')
        $(`.moreClassify[data-index='${index}']`).css('display','block')
        $('#mainContent .left ul li').removeClass('active')
        $(this).addClass('active')
    })

    $('#mainContent .left ul li').on('mouseout',function(){
            $('#mainContent .left ul li').removeClass('active')
            $('.moreClassify').css('display','none')
        })
}
//点击9.9包邮跳转到包邮界面
function jumpTobaoyou(){
    $('#nav ul').on('click','li',function(){
        if($(this).text() == '9块9包邮'){
            location.href = './baoyou.html'
        }
    })
}
//点击大额券跳转到超值大额券
function jumpToQuan(){
    $('#nav ul').on('click','li',function(){
        if($(this).text() == '超值大额券'){
            location.href = './youhui.html'
        }
    })
}
//点击商品列表跳转到对应商品详情页
function onProductDetail(id){
    location.href = './detail.html?id='+id
}

// 跳转至购物车
function jumpToShoppingCart(){
    $('#nav ul').on('click','li',function(){
        if($(this).text() == '购物车'){
            location.href = './shoppingCart.html'
        }
    })
}


getLogin()
changeLogin()
register()
login()

showUser()
getBanner()
getProductList()
getMore()
getMoreClassify()
jumpTobaoyou()
jumpToQuan()
jumpToShoppingCart()